package com.ruoyi.combat.service.socialmedia.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.ruoyi.combat.domain.CombatMethod;
import com.ruoyi.combat.domain.userlocation.CombatBlog;
import com.ruoyi.combat.domain.userlocation.CombatRelation;
import com.ruoyi.combat.domain.userlocation.CombatUser;
import com.ruoyi.combat.domain.userlocation.CombatWarn;
import com.ruoyi.combat.service.ICombatMethodService;
import com.ruoyi.combat.service.socialmedia.CombatCrawlService;
import com.ruoyi.combat.service.userlocation.ICombatBlogService;
import com.ruoyi.combat.service.userlocation.ICombatRelationService;
import com.ruoyi.combat.service.userlocation.ICombatUserService;
import com.ruoyi.combat.service.userlocation.ICombatWarnService;
import com.ruoyi.combat.util.CoordinateUtils;
import com.ruoyi.combat.util.MethodUseUtils;
import com.ruoyi.combat.util.weibo.WeiboApiUtil;
import com.ruoyi.common.utils.StringUtils;
import com.sun.javafx.collections.ListListenerHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Slf4j
@Service
public class CombatCrawlServiceImpl implements CombatCrawlService {

    @Autowired
    private ICombatUserService combatUserService;
    @Autowired
    private ICombatMethodService combatMethodService;
    @Autowired
    private MethodUseUtils methodUseUtils;
    @Autowired
    private ICombatWarnService combatWarnService;
    @Autowired
    private ICombatBlogService combatBlogService;
    @Autowired
    private ICombatRelationService combatRelationService;
    @Autowired
    private WeiboApiUtil weiboApiUtil;

    @Override
    public void crawlWeiboByUserId(String id) {
        CombatUser user = combatUserService.selectCombatUserById(Long.parseLong(id));
        String userId = user.getUserId();
        String token = user.getToken();
//        获取最新微博
        List<String> list = new ArrayList<>();
        list.add(userId);
        String latestWeibo = weiboApiUtil.getLatestWeibo(list);
        if (StringUtils.isNotEmpty(token)) {
            List<Map<String, String>> listMap = new ArrayList<>();
            Map<String, String> data = new HashMap<>();
            data.put("type", "follow");
            data.put("cookie", token);
            data.put("user_id", userId);
            listMap.add(data);
            String friends = weiboApiUtil.getFriends(listMap);
        }
    }


    /**
     * 采集最新的博文数据
     *
     * @param data
     */
    public void makeBlogData(String data) {
        Map bean = JSONUtil.toBean(data, Map.class);
        Object o = bean.get("statuses");
        if (o != null) {
            JSONArray statuses = (JSONArray) o;
            if (statuses.size() > 0) {
                for (int i = 0; i < statuses.size(); i++) {
                    Object o1 = statuses.get(i);
                    Map bean1 = JSONUtil.toBean(String.valueOf(o1), Map.class);
                    String idstr = String.valueOf(bean1.get("idstr"));
                    CombatBlog combatBlog = new CombatBlog();
                    combatBlog.setBlogId(idstr);
                    List<CombatBlog> combatBlogs = combatBlogService.selectCombatBlogList(combatBlog);
                    if (combatBlogs.size() <= 0) {
                        Map user = (Map) bean1.get("user");
                        combatBlog.setUserId(String.valueOf(user.get(idstr)));
                        combatBlog.setUsername(String.valueOf(user.get("screen_name")));
                        String time = String.valueOf(bean1.get("created_at"));
                        combatBlog.setReportime(DateUtil.parse(time, "EEE MMM dd HH:mm:ss Z yyyy"));
                        combatBlog.setReportContent(String.valueOf(bean1.get("text")));
                        Object o2 = bean1.get("pic_urls");
                        if (o2 != null) {
                            String reportImages = "";
                            List<Map> list = (List<Map>) bean1.get("pic_urls");
                            for (Map map : list) {
                                if (StringUtils.isNotEmpty(reportImages)) {
                                    reportImages = reportImages + "," + String.valueOf(map.get("thumbnail_pic"));
                                } else {
                                    reportImages = String.valueOf(map.get("thumbnail_pic"));
                                }
                                combatBlog.setReportImages(reportImages);
                            }
                        }
                        combatBlog.setCrawltime(new Date());
                        combatBlog.setBlogPlate("微博");
                        if (bean1.get("comments_count") == null) {
                            combatBlog.setBlogCommentNum(0l);
                        } else {
                            String s = String.valueOf(bean1.get("comments_count"));
                            combatBlog.setBlogCommentNum(Long.parseLong(s));
                        }

                        Object o3 = bean1.get("reposts_count");
                        if (o3 == null) {
                            combatBlog.setBlogForwardNum(0l);
                        } else {
                            String s = String.valueOf(bean1.get("reposts_count"));
                            combatBlog.setBlogForwardNum(Long.parseLong(s));
                        }
                        Object o4 = bean1.get("attitudes_count");
                        if (o4 == null) {
                            combatBlog.setBlogTolikeNum(0l);
                        } else {
                            String s = String.valueOf(bean1.get("attitudes_count"));
                            combatBlog.setBlogTolikeNum(Long.parseLong(s));
                        }
                        combatBlog.setStatus("0");
                        combatBlogService.insertCombatBlog(combatBlog);
                    }
                }
            }
        }
    }

    /**
     * c采集用户最新关注数据
     *
     * @param data
     * @param userId
     */
    public void makefriendsData(String data, String userId) {
        CombatUser combatUser = combatUserService.selectCombatUserByUserId(userId);
        Map bean = JSONUtil.toBean(data, Map.class);
        Object o = bean.get("users");
        if (o != null) {
            JSONArray users = (JSONArray) o;
            for (int i = 0; i < users.size(); i++) {
                Object o1 = users.get(i);
                Map user = JSONUtil.toBean(String.valueOf(o1), Map.class);
                String targetid = String.valueOf(user.get("idstr"));
                CombatRelation combatRelation = new CombatRelation();
                combatRelation.setUserid(userId);
                combatRelation.setTargetid(targetid);
                List<CombatRelation> combatRelations = combatRelationService.selectCombatRelationList(combatRelation);
                if (combatRelations.size() <= 0) {
                    combatRelation.setRelation("关注");
                    combatRelation.setPlate("微博");
                    combatRelation.setUsername(combatUser.getUserNickname());
                    combatRelation.setUserCity(combatUser.getUserHomeAddr());
                    combatRelation.setTargetName(String.valueOf(user.get("screen_name")));
                    combatRelation.setTargetCity(String.valueOf(user.get("city")));
                    combatRelationService.insertCombatRelation(combatRelation);
                } else {
                    //更新用户关注状态
                    CombatRelation combatRelation1 = combatRelations.get(0);
                    if ("1".equals(combatRelation1.getStatus())) {
                        combatRelation1.setStatus("0");
                        combatRelationService.updateCombatRelation(combatRelation1);
                    }
                }
            }
        }
    }


    @Override
    public void crawlWeiboByUserIds(Long[] ids) {
        if (ids != null && ids.length > 0) {
            List<String> list = new ArrayList<>();
            List<Map<String, String>> listMap = new ArrayList<>();
            String token = "";
            for (Long id : ids) {
                CombatUser user = combatUserService.selectCombatUserById(id);
                String userId = user.getUserId();
                //我是调取爬虫接口的逻辑代码
                token = user.getToken();
                list.add(userId);
//            更新用户数据，获取用户发布的微博内容
                if (StringUtils.isNotEmpty(token)) {
                    Map<String, String> data = new HashMap<>();
                    data.put("type", "follow");
                    data.put("cookie", token);
                    data.put("user_id", userId);
                    listMap.add(data);
                }

            }
            String latestWeibo = weiboApiUtil.getLatestWeibo(list);
            String friends = weiboApiUtil.getFriends(listMap);
        }else{
            crawlAllWeiboByUserIds();
        }
    }

    @Override
    public void moreWeiboInfo(String[] ids) {
        if (ids != null && ids.length > 0) {
            List<String> list = new ArrayList<>();
            List<Map<String, String>> listMap = new ArrayList<>();
            String token = "";
            for (String id : ids) {
                CombatUser user = combatUserService.selectCombatUserByUserId(id);
                String userId = user.getUserId();
                //我是调取爬虫接口的逻辑代码
                token = user.getToken();
                list.add(userId);
//            更新用户数据，获取用户发布的微博内容
                if (StringUtils.isNotEmpty(token)) {
                    Map<String, String> data = new HashMap<>();
                    data.put("type", "follow");
                    data.put("cookie", token);
                    data.put("user_id", userId);
                    listMap.add(data);
                }

            }
            String latestWeibo = weiboApiUtil.getLatestWeibo(list);
            String friends = weiboApiUtil.getFriends(listMap);
        }else{
            crawlAllWeiboByUserIds();
        }
    }

    @Override
    public void crawlAllWeiboByUserIds() {
        List<CombatUser> listData = combatUserService.selectCombatUserList(new CombatUser());
        List<String> list = new ArrayList<>();
        List<Map<String, String>> listMap = new ArrayList<>();
        for (CombatUser user : listData) {
            String userId = user.getUserId();
            list.add(userId);
            //我是调取爬虫接口的逻辑代码
            String token = user.getToken();
            if (StringUtils.isNotEmpty(token)) {
                Map<String, String> data = new HashMap<>();
                data.put("type", "follow");
                data.put("cookie", token);
                data.put("user_id", userId);
                listMap.add(data);
            }
        }
        String latestWeibo = weiboApiUtil.getLatestWeibo(list);
        String friends = weiboApiUtil.getFriends(listMap);
    }

    /**
     * 检查微博文本内容是否安全
     *
     * @param mothodId
     * @param content  ['郑州的美好记忆 二七广场逛了 油画厂值得打卡 瑞光有点失望']
     */
    @Override
    public CombatWarn checkWeiboContent(Long mothodId, String userId, String content) {
        CombatUser combatUser = combatUserService.selectCombatUserByUserId(userId);
        if (combatUser == null) {
            return null;
        }
        List<String> list = new ArrayList<>();
        list.add(content);
        Map<String, Object> stringObjectMap = methodUseUtils.methodUseLogs(15l, JSONUtil.toJsonStr(list));
        String locationPos = "";
        CombatWarn combatWarn = new CombatWarn();
        try {
            if(stringObjectMap!=null) {
                locationPos = String.valueOf(stringObjectMap.get("city-district"));
                String province = String.valueOf(stringObjectMap.get("province"));
                Map coordinate = (Map) stringObjectMap.get("coordinate");//获取坐标；
                try {
                    List list1 = new ArrayList();
                    list1.add(coordinate);
                    combatWarn.setCheckResult(JSONUtil.toJsonStr(list1));
                } catch (Exception e) {
                }
                double lat = Double.parseDouble(String.valueOf(coordinate.get("lat")));
                double lng = Double.parseDouble(String.valueOf(coordinate.get("lng")));
                //与用户家庭、工作地址进行坐标进行比较；
                String userHomeLat = combatUser.getUserHomeLat();
                String userHomeLon = combatUser.getUserHomeLon();
                Long home = 1000L;
                if (StringUtils.isNotEmpty(userHomeLat) && StringUtils.isNotEmpty(userHomeLon)) {
                    double homeLat = Double.parseDouble(String.valueOf(userHomeLat));
                    double homeLon = Double.parseDouble(String.valueOf(userHomeLon));
                    home = CoordinateUtils.calculateGEODistance(lat, lng, homeLat, homeLon);
                }

                String userWorkLat = combatUser.getUserWorkLat();
                String userWorkLon = combatUser.getUserWorkLon();
                Long work = 1000L;
                if (StringUtils.isNotEmpty(userWorkLat) && StringUtils.isNotEmpty(userWorkLon)) {
                    double workLat = Double.parseDouble(String.valueOf(userWorkLat));
                    double workLon = Double.parseDouble(String.valueOf(userWorkLon));
                    work = CoordinateUtils.calculateGEODistance(lat, lng, workLat, workLon);
                }
                //插入警告记录
                if (home < 30 || work < 30) {
                    combatWarn.setUserid(userId);
                    combatWarn.setUsername(combatUser.getUserName());
                    combatWarn.setLocationBasis("文本定位");
                    combatWarn.setLocationLat(String.valueOf(lat));//定位纬度
                    combatWarn.setLocationLon(String.valueOf(lng));//定位经度
                    combatWarn.setProvince(province);//定位经度

                    String leak = "家庭地址";
                    if (work < home) {
                        leak = "工作地址";
                    }
                    combatWarn.setLocationLeak(leak);//泄露地点
                    combatWarn.setLocationPos(locationPos);//定位地点

                }else{
                    combatWarn.setLocationPos(locationPos);//定位地点
                }
            }
        } catch (NumberFormatException e) {

        }

        return combatWarn;
    }

    /**
     * 检查微博图片内容是否安全
     *
     * @param mothodId
     * @param userId
     * @param content  {
     *                 "image": "/9j/4AAQSkZJRB.....+4F7nbDMf/9k=",
     *                 "city": "上海",
     *                 "topk": 1  默认20
     *                 }
     */
    @Override
    public CombatWarn checkWeiboImage(Long mothodId, String userId, String content, String city) {
        CombatWarn combatWarn = new CombatWarn();
        //todo 调整
        try {
            CombatUser combatUser = combatUserService.selectCombatUserByUserId(userId);
            String userHomeLat1 = combatUser.getUserHomeLat();
            String userHomeLon1 = combatUser.getUserHomeLon();
            String userWorkLat1 = combatUser.getUserWorkLat();
            String userWorkLon1 = combatUser.getUserWorkLon();

            List home_location = new ArrayList();
            home_location.add(userHomeLon1);
            home_location.add(userHomeLat1);

            List work_location = new ArrayList();
            work_location.add(userWorkLon1);
            work_location.add(userWorkLat1);


            Map<String, Object> data = new HashMap();
//        imgGeo = "上海";
            data.put("image", content);
            data.put("city", city);
            data.put("topk", 10);
            data.put("home_location", home_location);
            data.put("work_location", work_location);
            String jsonStr = JSONUtil.toJsonStr(data);
            log.info(jsonStr);
            Map<String, Object> stringObjectMap = methodUseUtils.methodUseLogs(mothodId, jsonStr);
            List<Map> gps = (List<Map>) stringObjectMap.get("gps");

            List<String> location = (List<String>) stringObjectMap.get("location");
            if(location==null){
                return combatWarn;
            }
            combatWarn.setCheckResult(JSONUtil.toJsonStr(stringObjectMap));
            for (int i = 0; i < location.size(); i++) {
                String locationPos = location.get(i);
                String jsonStr1 = JSONUtil.toJsonStr(gps.get(i));
                List<Double> coordinate = JSONUtil.toList(jsonStr1,Double.class);
//                Map coordinate = gps.get(i);//获取坐标；
                double lat = coordinate.get(1);
                double lng = coordinate.get(0);
                //与用户家庭、工作地址进行坐标进行比较；
                String userHomeLat = combatUser.getUserHomeLat();
                String userHomeLon = combatUser.getUserHomeLon();
                Long home = 1000L;
                if (StringUtils.isNotEmpty(userHomeLat) && StringUtils.isNotEmpty(userHomeLon)) {
                    double homeLat = Double.parseDouble(String.valueOf(userHomeLat));
                    double homeLon = Double.parseDouble(String.valueOf(userHomeLon));
                    home = CoordinateUtils.calculateGEODistance(lat, lng, homeLat, homeLon);
                }

                String userWorkLat = combatUser.getUserWorkLat();
                String userWorkLon = combatUser.getUserWorkLon();
                Long work = 1000L;
                if (StringUtils.isNotEmpty(userWorkLat) && StringUtils.isNotEmpty(userWorkLon)) {
                    double workLat = Double.parseDouble(String.valueOf(userWorkLat));
                    double workLon = Double.parseDouble(String.valueOf(userWorkLon));
                    work = CoordinateUtils.calculateGEODistance(lat, lng, workLat, workLon);
                }
                //插入警告记录
                if (home < 30 || work < 30) {
                    combatWarn.setUserid(userId);
                    combatWarn.setUsername(combatUser.getUserName());
                    combatWarn.setLocationBasis("图像定位");
                    combatWarn.setLocationLat(String.valueOf(lat));//定位纬度
                    combatWarn.setLocationLon(String.valueOf(lng));//定位经度

                    String leak = "家庭地址";
                    if (work < home) {
                        leak = "工作地址";
                    }
                    combatWarn.setLocationLeak(leak);//泄露地点
                    combatWarn.setLocationPos(locationPos);//定位地点

                    break;
                }
            }
        } catch (NumberFormatException e) {

        }
        return combatWarn;
    }
    @Override
    public CombatWarn checkWeiboVideo(Long mothodId, String userId, String content, String city) {
        CombatWarn combatWarn = new CombatWarn();
        //todo 调整
        try {
            CombatUser combatUser = combatUserService.selectCombatUserByUserId(userId);
            String userHomeLat1 = combatUser.getUserHomeLat();
            String userHomeLon1 = combatUser.getUserHomeLon();
            String userWorkLat1 = combatUser.getUserWorkLat();
            String userWorkLon1 = combatUser.getUserWorkLon();

            List home_location = new ArrayList();
            home_location.add(userHomeLon1);
            home_location.add(userHomeLat1);

            List work_location = new ArrayList();
            work_location.add(userWorkLon1);
            work_location.add(userWorkLat1);


            Map<String, Object> data = new HashMap();
//        imgGeo = "上海";
            data.put("frames", content);
            data.put("city", city);
            data.put("topk", 10);
            data.put("home_location", home_location);
            data.put("work_location", work_location);
            String jsonStr = JSONUtil.toJsonStr(data);
            Map<String, Object> stringObjectMap = methodUseUtils.methodUseLogs(mothodId, jsonStr);
            List<Map> gps = (List<Map>) stringObjectMap.get("gps");

            List<String> location = (List<String>) stringObjectMap.get("location");
            if(location==null){
                return combatWarn;
            }
            combatWarn.setCheckResult(JSONUtil.toJsonStr(stringObjectMap));
            for (int i = 0; i < location.size(); i++) {
                String locationPos = location.get(i);
                String jsonStr1 = JSONUtil.toJsonStr(gps.get(i));
                List<Double> coordinate = JSONUtil.toList(jsonStr1,Double.class);
//                Map coordinate = gps.get(i);//获取坐标；
                double lat = coordinate.get(1);
                double lng = coordinate.get(0);
                //与用户家庭、工作地址进行坐标进行比较；
                String userHomeLat = combatUser.getUserHomeLat();
                String userHomeLon = combatUser.getUserHomeLon();
                Long home = 1000L;
                if (StringUtils.isNotEmpty(userHomeLat) && StringUtils.isNotEmpty(userHomeLon)) {
                    double homeLat = Double.parseDouble(String.valueOf(userHomeLat));
                    double homeLon = Double.parseDouble(String.valueOf(userHomeLon));
                    home = CoordinateUtils.calculateGEODistance(lat, lng, homeLat, homeLon);
                }

                String userWorkLat = combatUser.getUserWorkLat();
                String userWorkLon = combatUser.getUserWorkLon();
                Long work = 1000L;
                if (StringUtils.isNotEmpty(userWorkLat) && StringUtils.isNotEmpty(userWorkLon)) {
                    double workLat = Double.parseDouble(String.valueOf(userWorkLat));
                    double workLon = Double.parseDouble(String.valueOf(userWorkLon));
                    work = CoordinateUtils.calculateGEODistance(lat, lng, workLat, workLon);
                }
                //插入警告记录
                if (home < 30 || work < 30) {
                    combatWarn.setUserid(userId);
                    combatWarn.setUsername(combatUser.getUserName());
                    combatWarn.setLocationBasis("图像定位");
                    combatWarn.setLocationLat(String.valueOf(lat));//定位纬度
                    combatWarn.setLocationLon(String.valueOf(lng));//定位经度

                    String leak = "家庭地址";
                    if (work < home) {
                        leak = "工作地址";
                    }
                    combatWarn.setLocationLeak(leak);//泄露地点
                    combatWarn.setLocationPos(locationPos);//定位地点

                    break;
                }
            }
        } catch (NumberFormatException e) {

        }
        return combatWarn;
    }


}
